package com.xiaomo.gitee.datamanager.service.category.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaomo.gitee.datamanager.aspect.log.anno.SysLog;
import com.xiaomo.gitee.datamanager.cache.RedisCacheManager;
import com.xiaomo.gitee.datamanager.mapper.*;
import com.xiaomo.gitee.datamanager.entity.CClassInfo;

import com.xiaomo.gitee.datamanager.entity.ClassInfo;
import com.xiaomo.gitee.datamanager.entity.Images;
import com.xiaomo.gitee.datamanager.service.category.ClassInfoService;
import com.xiaomo.gitee.datamanager.service.tag.impl.CategoryTagServiceImpl;
import com.xiaomo.gitee.datamanager.util.ImagesSequenceUtils;
import com.xiaomo.gitee.datamanager.util.RedisUtils;
import lombok.*;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.Executor;

@EqualsAndHashCode(callSuper = true)
@Component
@Data
@RequiredArgsConstructor
public class ClassInfoServiceImpl extends ServiceImpl<ClassInfoMapper, ClassInfo>
        implements ClassInfoService {

    private final CClassInfoMapper childClass;
    private final ClassInfoMapper parentClass;
    private final ImagedesMapper imagedesMapper;
    private final ImagesMapper imagesMapper;
    private final ImageTagMapper imageTagMapper;
    private final CategoryTagServiceImpl categoryTagService;
    private final ImagesSequenceUtils imagesSequenceUtils;
    private final Executor threadPool;

    @Value("${upload.dir}")
    private String uploadDirectory;

    @Override
    public List<CClassInfo> getChildClasses() {
        return childClass.selectAll();
//        return redisCacheManager.getChildClasses();
    }

    @Override
    public List<ClassInfo> getParentClasses() {
        return parentClass.selectAll();
    }

    @Override
    public ClassInfo getParentClassById(Long id) {
        return parentClass.selectById(id);
    }

    @Override
    public CClassInfo getChildClassById(Long id) {
        return childClass.selectOneById(id);
    }

    @Override
    public List<CClassInfo> getChildClassesByPClass(String parentClassId) {
        if (parentClassId.equalsIgnoreCase("all")) {
            return childClass.selectAll().stream().peek(category -> {
                category.setName(parentClass.selectById(category.getP_class_id()).getName() + ": " + category.getName());
                QueryWrapper<Images> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("classification",category.getId());
                category.setImageAmount(imagesMapper.selectCount(queryWrapper));
            }).toList();
        } else {
            long pId = Long.parseLong(parentClassId);
            return childClass.selectByPClassId(pId).stream().peek(category -> {
                QueryWrapper<Images> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("classification",category.getId());
                category.setImageAmount(imagesMapper.selectCount(queryWrapper));
            }).toList();
        }
    }

    /**
     * @param classInfo
     * @return int
     */
    @SysLog("创建大类别")
    public int insertParentClass(ClassInfo classInfo) {
        if (parentClass.selectById(classInfo.getId()) != null) {
            return -1;
        }
        if (!parentClass.selectByName(classInfo.getName()).isEmpty()) {
            return -2;
        }
        parentClass.insert(classInfo);

        MDC.put("名称", classInfo.getName());

        return 0;
    }

    @SysLog("创建数据集")
    public int insertChildClass(CClassInfo cClassInfo) {
        if (childClass.selectOneById(cClassInfo.getId()) != null) {
            return -1;
        }
        for (CClassInfo info : childClass.selectByPClassId(cClassInfo.getP_class_id())) {
            if (info.getName().equalsIgnoreCase(cClassInfo.getName())) {
                return -2;
            }
        }
        childClass.insert(cClassInfo);

        MDC.put("数据集", cClassInfo.getName());
        MDC.put("大类别Id", cClassInfo.getP_class_id().toString());

        return 0;
    }

    @SysLog("删除数据集")
    public void deleteChildClass(Long category) {
        String s = File.separator;
        String sDir = uploadDirectory + s + "small";
        String bDir = uploadDirectory + s + "original";
        List<Images> images = imagesMapper.selectAllByClassification(category);

/*        threadPool.execute(() -> {
            images.forEach(image -> redisUtils.lRemove("category:" + category,0,image));
        });*/

        categoryTagService.deleteAllTagsOfSet(category);
        for (Images id : images) {
            imageTagMapper.deleteByImageId(id.getId());
            try {
                Files.deleteIfExists(Paths.get(sDir + s + id.getId() + ".jpg"));
                Files.deleteIfExists(Paths.get(bDir + s + id.getId() + ".jpg"));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
        imagedesMapper.deleteByCategory(category);
        imagesMapper.deleteByClassification(category);
        childClass.deleteById(category);
        imagesSequenceUtils.loadImagesSequence();

        MDC.put("数据集Id", category.toString());

    }
}
